package org.shj.book2.chapter06;

public class Data {

	private final char[] buffer;
	private final ReadWriteLock lock = new ReadWriteLock();
	
	public Data(int size){
		this.buffer = new char[size];
		for(int i = 0 ; i < size; i++){
			buffer[i] = '*';
		}
	}
	
	public char[] read() throws InterruptedException{
		lock.readLock();
		try{
			return doRead();
		}finally{
			lock.readUnlock();
		}
	}
	
	public void write(char c) throws InterruptedException{
		lock.writeLock();
		try{
			doWrite(c);
		}finally{
			lock.writeUnlock();
		}
	}
	
	private char[] doRead(){
		char[] newbuf = new char[buffer.length];
		for(int i = 0 ; i < buffer.length; i++){
			newbuf[i] = buffer[i];
		}
		
		slowly();
		return newbuf;
	}
	
	private void doWrite(char c){
		for(int i = 0 ; i < buffer.length; i++){
			buffer[i] = c;
			slowly(); //在循环里调用，模拟写的操作会比读的操作要花的时间长
		}
	}
	
	//模拟比较花费时间的操作
	private void slowly(){
		try{
			Thread.sleep(50);
		}catch(InterruptedException e){
			
		}
	}
}
